package com.omronble.bp_broadcast.activity;

import androidx.core.content.FileProvider;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.omronble.bp_broadcast.R;
import com.omronble.bp_broadcast.bean.UpdateBean;
import com.omronble.bp_broadcast.tools.DeviceMethod;
import com.omronble.bp_broadcast.tools.Utils;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.File;

import okhttp3.Call;

public class UpdateActivity extends BaseActivity {

    private String path = Environment.getExternalStorageDirectory().getAbsolutePath();
    private TextView tvVersionNew , tvVersionCur ,tvBp ;
    private ProgressBar pb ;
    private UpdateBean bean ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update);
//        StatusBarUtil.setColor(this, Color.BLACK);
        tvVersionNew = findViewById(R.id.tvVersionNew);
        tvVersionCur = findViewById(R.id.tvVersionCur);
        tvBp = findViewById(R.id.tvBp);
        pb = findViewById(R.id.pb);
        tvVersionCur.setText( "当前版本：v" + Utils.getAppVersionName(this) );
        bean = (UpdateBean) getIntent().getSerializableExtra("UpdateBean");
        if ( null == bean ){
            finish();
            return;
        }
        tvVersionNew.setText( "最新版本：v" + bean.getClientVersion() );

        String apkName = "bp.apk";

        RxPermissions permissions = new RxPermissions(this);
        permissions.setLogging(true);
        permissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe( bool -> {
                    if ( bool )
                        downloadFile(bean.getDownloadUrl(),apkName);
                    else {
                        Toast.makeText(UpdateActivity.this, "文件系统读写权限没有打开。。", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                });

    }

    /**
     * 下载附件
     */
    public void downloadFile(String url,String houZuiName){

        OkHttpUtils.get()
                .url(url)
//                .url("https://dldir1.qq.com/weixin/android/weixin7010android1580.apk")
                .build()
                .execute(new FileCallBack(path,houZuiName) {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("info: ", "onError :" + e.getMessage());
                    }

                    @Override
                    public void inProgress(float progress, long total, int id) {
                        super.inProgress(progress, total, id);
                        Log.e("info: ","inProgress"+(int)(100*progress));
                        pb.setProgress( (int)(100*progress) );
                        tvBp.setText( (int)(100*progress) + "%" );
                    }

                    @Override
                    public void onResponse(File downloadFile, int id) {
//                       installAPK(downloadFile);
                        installHuaweiAPK(downloadFile);
                       finish();
                    }
                });
    }


    /**
     * 华为静默安装
     * @param file
     */
    private void installHuaweiAPK(File file){
        /*10.0(29)及以后参数packagePath需要使用File Content Provider的格式，并仅限应用数据目录下文件。*/
        String packagePath;
        if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q )
            packagePath = FileProvider.getUriForFile(this,this.getPackageName() + ".fileProvider",file).toString();
        else
            packagePath =  file.getAbsolutePath();
        DeviceMethod.getInstance(this).installPackage(packagePath);
    }

    /**
     * 安装Apk
     */
    private void installAPK(File apkFile) {
        if (null == apkFile || !apkFile.exists()) {
            return;
        }
        Log.d( getClass().getSimpleName() , ""+Utils.isRoot() );
        if ( Utils.isRoot() ){
            Utils.install( apkFile.getPath() );
            return;
        }

        Intent intent = new Intent(Intent.ACTION_VIEW);
//      安装完成后，启动app（源码中少了这句话）
        if (null != apkFile) {
            try {
                //兼容7.0
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    Uri contentUri = FileProvider.getUriForFile(this, this.getPackageName() + ".fileProvider", apkFile);
                    intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                    //兼容8.0
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        boolean hasInstallPermission = this.getPackageManager().canRequestPackageInstalls();
                        if (!hasInstallPermission) {
                            startInstallPermissionSettingActivity();
                            return;
                        }
                    }
                } else {
                    intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                }
                if (this.getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
                    this.startActivity(intent);
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }

    private void startInstallPermissionSettingActivity() {
        //注意这个是8.0新API
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        this.startActivity(intent);
    }

    //判断文件是否存在
    public boolean fileIsExists(String strFile) {
        try {
            File f=new File(strFile);
            if(!f.exists())
                return false;
        }
        catch (Exception e) {
            return false;
        }
        return true;
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
    }

    private void getAppDetailSettingIntent(Context context) {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings","com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
        }
        startActivity(localIntent);
    }


}
